import logging
import time
import random
from datetime import datetime
from faker import Faker
import os
from flask import Flask, render_template_string, Response
# 新增：导入 Kafka 相关模块
try:
    from kafka import KafkaProducer
    import json
    KAFKA_AVAILABLE = True
except ImportError:
    KAFKA_AVAILABLE = False

# 初始化Faker和日志配置
fake = Faker()
LOG_FORMAT = '{"remote_addr": "%(remote_addr)s", "remote_user": "%(remote_user)s", "time_local": "%(time_local)s", "request": "%(request)s", "status": "%(status)s", "body_bytes_sent": "%(body_bytes_sent)s", "http_referer": "%(http_referer)s", "http_user_agent": "%(http_user_agent)s"}'
user_agents = [
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
    'PostmanRuntime/7.29.2',
    'curl/7.68.0'
]

# 新增：Kafka 配置
KAFKA_BOOTSTRAP_SERVERS = os.environ.get('KAFKA_BOOTSTRAP_SERVERS', '192.168.3.81:30092')
KAFKA_TOPIC = os.environ.get('KAFKA_TOPIC', 'app-logs')
kafka_producer = None

def setup_logger():
    logger = logging.getLogger('nginx_simulator')
    logger.setLevel(logging.INFO)
    
    # 添加控制台处理器
    console_handler = logging.StreamHandler()
    console_handler.setFormatter(logging.Formatter(LOG_FORMAT))
    logger.addHandler(console_handler)
    
    # 确保日志目录存在
    log_dir = 'logs'
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)
    
    # 添加文件处理器
    file_handler = logging.FileHandler(os.path.join(log_dir, 'app-logging.log'))
    file_handler.setFormatter(logging.Formatter(LOG_FORMAT))
    logger.addHandler(file_handler)
    
    return logger

# 新增：初始化 Kafka 生产者
def setup_kafka_producer():
    global kafka_producer
    if KAFKA_AVAILABLE:
        try:
            kafka_producer = KafkaProducer(
                bootstrap_servers=KAFKA_BOOTSTRAP_SERVERS,
                value_serializer=lambda v: json.dumps(v).encode('utf-8')
            )
            print(f"Kafka producer initialized. Sending logs to {KAFKA_BOOTSTRAP_SERVERS}, topic: {KAFKA_TOPIC}")
        except Exception as e:
            print(f"Failed to initialize Kafka producer: {e}")
            kafka_producer = None
    else:
        print("Kafka library not available. Install kafka-python to enable Kafka support.")

log_count = 0

def generate_log_data():
    global log_count
    log_count += 1
    return {
        'remote_addr': fake.ipv4(),
        'remote_user': '-',
        'time_local': datetime.now().strftime('%d/%b/%Y:%H:%M:%S +0800'),
        'request': f'GET /{fake.uri_path()} HTTP/1.1',
        'status': 200,
        'body_bytes_sent': random.randint(200, 5000),
        'http_referer': fake.url(),
        'http_user_agent': random.choice(user_agents)
    }

# 修改：在生成日志时发送到 Kafka
def log_generator():
    global kafka_producer
    logger = setup_logger()
    try:
        while True:
            log_data = generate_log_data()
            logger.info('', extra=log_data)
            
            # 新增：发送日志到 Kafka
            if kafka_producer:
                try:
                    kafka_producer.send(KAFKA_TOPIC, log_data)
                except Exception as e:
                    print(f"Failed to send log to Kafka: {e}")
            
            time.sleep(5)
    except KeyboardInterrupt:
        print("\n日志生成已停止")
        # 新增：关闭 Kafka 生产者
        if kafka_producer:
            kafka_producer.close()

app = Flask(__name__)

LOG_FILE_PATH = os.path.join('logs', 'app-logging.log')

@app.route('/')
def show_logs():
    if not os.path.exists(LOG_FILE_PATH):
        logs = "日志文件不存在。"
    else:
        with open(LOG_FILE_PATH, encoding='utf-8') as f:
            logs = f.read().replace('\n', '<br>')
    html = f"""
    <html>
    <head><title>日志展示</title></head>
    <body>
        <h2>生成的日志</h2>
        <div style="font-family:monospace;white-space:pre-wrap;">{logs}</div>
    </body>
    </html>
    """
    return html

@app.route('/metrics')
def metrics():
    # 返回 Prometheus 格式的监控数据
    metric_data = f"""# HELP app_log_generated_total 日志生成总次数
# TYPE app_log_generated_total counter
app_log_generated_total {log_count}
"""
    return Response(metric_data, mimetype='text/plain')

if __name__ == '__main__':
    import threading

    # 新增：初始化 Kafka 生产者
    setup_kafka_producer()

    # 启动日志生成线程
    t = threading.Thread(target=log_generator, daemon=True)
    t.start()

    # 启动Flask服务
    app.run(host='0.0.0.0', port=9527)